import { loadEnv, defineConfig } from 'vite';
import { resolve } from 'path';
import { wrapperEnv } from './build/utils';
import { createVitePlugins } from './build/vite/plugin';
import { createProxy } from './build/vite/proxy';

// https://vitejs.dev/config/
// https://github.com/anncwb/vite-plugin-mock/blob/HEAD/README.zh_CN.md
export default defineConfig(({ command, mode }) => {
	const root = process.cwd();

	const env = loadEnv(mode, root);

	// The boolean type read by loadEnv is a string. This function can be converted to boolean type
	const viteEnv = wrapperEnv(env);

	const { VITE_OPEN, VITE_PORT, VITE_PROXY, VITE_PUBLIC_PATH } = viteEnv;

	const isBuild = command === 'build';
	return {
		root: process.cwd(),
		base: VITE_PUBLIC_PATH,
		resolve: {
			alias: {
				'@': resolve(__dirname, 'src'),
				'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
			},
		},
		plugins: createVitePlugins(viteEnv, isBuild),
		optimizeDeps: {
			include: [
				'element-plus/lib/locale/lang/zh-cn',
				'element-plus/lib/locale/lang/en',
				'element-plus/lib/locale/lang/zh-tw',
			],
		},
		server: {
			host: true,
			port: VITE_PORT,
			open: VITE_OPEN,
			// Load proxy configuration from .env
			proxy: createProxy(VITE_PROXY),
		},
		build: {
			outDir: 'dist',
			minify: 'esbuild',
			sourcemap: false,
			// Turning off brotliSize display can slightly reduce packaging time
			brotliSize: false,
			chunkSizeWarningLimit: 2000,
		},
		define: {
			// https://www.npmjs.com/package/vue-i18n/v/9.1.7
			__VUE_I18N_LEGACY_API__: false,
			__VUE_I18N_FULL_INSTALL__: false,
			__INTLIFY_PROD_DEVTOOLS__: false,
		},
	};
});
